#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdlib.h>

  struct ListNode {
     int val;
     struct ListNode *next;
  };


  struct ListNode* detectCycle(struct ListNode* head)
  {
      struct ListNode* slow = head;
      struct ListNode* fast = head;
      int flag = 0;
      if (head == NULL)
      {
          return NULL;
      }
      else
      {
          while (fast->next && fast->next->next)
          {
              fast = fast->next->next;
              slow = slow->next;
              if (fast == slow)
              {
                  flag = 1;
                  break;
              }
          }
          if (flag)
          {
              struct ListNode* ringnode = head;
              while (slow != ringnode)
              {
                  slow = slow->next;
                  ringnode = ringnode->next;
              }
              return slow;
          }
          else
          {
              return NULL;
          }
      }
      return NULL;
  }

int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n2;
    struct ListNode* head = n1;
    struct ListNode* ret = detectCycle(head);

    return 0;
}

